package com.hua.server.oauth.strategy;

import com.google.common.collect.Maps;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 处理 TypeAuthorizationServerHandler
 *
 * @author 华云龙
 * @date 2019-5-27
 */
@Component
public class TypeAuthorizationServerHandlerProcessor implements BeanFactoryPostProcessor {

    /**
     * 扫描注解TypeAuthorizationServerHandler
     *
     * @param configurableListableBeanFactory bean工厂
     * @throws BeansException bean exception
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

        HashMap<String, AuthorizationServerConfigurerStrategy> handlerMap = Maps.newHashMapWithExpectedSize(4);
        configurableListableBeanFactory.getBeansWithAnnotation(TypeAuthorizationServerHandler.class).forEach((str, obj) -> {
            if (obj instanceof AuthorizationServerConfigurerStrategy) {
                String value = obj.getClass().getAnnotation(TypeAuthorizationServerHandler.class).value();
                handlerMap.put(value, (AuthorizationServerConfigurerStrategy) obj);
            }
        });
        /// 注进spring中
        TypeAuthorizationServerHandlerContext typeAuthorizationServerHandlerContext = new TypeAuthorizationServerHandlerContext(handlerMap);
        configurableListableBeanFactory.registerSingleton(TypeAuthorizationServerHandlerContext.class.getName(), typeAuthorizationServerHandlerContext);
    }
}
